package com.example.demo.service.order.impl;

import com.alibaba.fastjson.JSON;
import com.example.demo.common.BaseErrorConfigEnum;
import com.example.demo.common.BasePageResponse;
import com.example.demo.common.ResultObject;
import com.example.demo.common.TerminologyConfigEnum;
import com.example.demo.dao.IExchangeRateDao;
import com.example.demo.dao.IOrderDao;
import com.example.demo.jooq.tables.daos.*;
import com.example.demo.jooq.tables.pojos.*;
import com.example.demo.model.po.ApplyPage;
import com.example.demo.model.po.OrderPage;
import com.example.demo.model.request.*;
import com.example.demo.model.response.ApplyPageResponse;
import com.example.demo.model.response.OrderPageResponse;
import com.example.demo.service.BaseBusinessServiceImpl;
import com.example.demo.service.order.IOrderService;
import com.example.demo.util.AssertUtils;
import com.example.demo.util.ClazzUtils;
import com.example.demo.util.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.modelmapper.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

@Service
public class IOrderServiceImpl extends BaseBusinessServiceImpl implements IOrderService {
    @Autowired
    private IOrderDao iOrderDao;

    @Autowired
    private ShopOrderDao orderDao;

    @Autowired
    private ApplyDao applyDao;

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private VisaCardDao visaCardDao;

    @Autowired
    private IExchangeRateDao iExchangeRateDao;

    @Override
    public ResultObject<BasePageResponse<OrderPageResponse>> queryPageOrderList(OrderPageRequest orderPageRequest) {
        ResultObject<BasePageResponse<OrderPageResponse>> responseResultObject = new ResultObject<>();
        List<OrderPage> vpsPages =  iOrderDao.queryPageOrderList(orderPageRequest);
        if(AssertUtils.isNotEmpty(vpsPages)){
            Integer integer =vpsPages.get(0).getTotalLine();
            List<OrderPageResponse> vpsResponses = (List<OrderPageResponse>)this.converterList(vpsPages,new TypeToken<List<OrderPageResponse>>() {}.getType() );
            //术语转换
            vpsResponses.forEach(visaResponse -> {
                if(AssertUtils.isNotNull(visaResponse.getOrderStatus())){
                    Arrays.stream(TerminologyConfigEnum.ORDER_STATUS.values()).filter(value->value.name().equals(visaResponse.getOrderStatus())).forEach(value->visaResponse.setOrderStatus(value.desc()));
                }
                if(AssertUtils.isNotNull(visaResponse.getAccountSource())){
                    Arrays.stream(TerminologyConfigEnum.ACCOUNT_SOURCE.values()).filter(value->value.name().equals(visaResponse.getAccountSource())).forEach(value->visaResponse.setAccountSource(value.desc()));
                }
                if(AssertUtils.isNotNull(visaResponse.getSite())){
                    Arrays.stream(TerminologyConfigEnum.SITE.values()).filter(value->value.name().equals(visaResponse.getSite())).forEach(value->visaResponse.setSite(value.desc()));
                }
            });
            BasePageResponse<OrderPageResponse> responseBasePageResponse =BasePageResponse.getData(orderPageRequest.getCurrentPage(),orderPageRequest.getPageSize(),integer,vpsResponses);
            responseResultObject.setData(responseBasePageResponse);
        }
        return responseResultObject;
    }

    @Override
    public ResultObject<BasePageResponse<ApplyPageResponse>> queryPageApplyList(ApplyPageRequest applyPageRequest) {
        ResultObject<BasePageResponse<ApplyPageResponse>> responseResultObject = new ResultObject<>();
        List<ApplyPage> vpsPages =  iOrderDao.queryPageApplyList(applyPageRequest);
        if(AssertUtils.isNotEmpty(vpsPages)){
            Integer integer =vpsPages.get(0).getTotalLine();
            List<ApplyPageResponse> vpsResponses = (List<ApplyPageResponse>)this.converterList(vpsPages,new TypeToken<List<ApplyPageResponse>>() {}.getType() );
            //术语转换
            vpsResponses.forEach(visaResponse -> {
                if(AssertUtils.isNotNull(visaResponse.getApplyStatus())){
                    Arrays.stream(TerminologyConfigEnum.APPLY_STATUS.values()).filter(value->value.name().equals(visaResponse.getApplyStatus())).forEach(value->visaResponse.setApplyStatus(value.desc()));
                }
                if(AssertUtils.isNotNull(visaResponse.getApplySource())){
                    Arrays.stream(TerminologyConfigEnum.APPLY_SOURCE.values()).filter(value->value.name().equals(visaResponse.getApplySource())).forEach(value->visaResponse.setApplySource(value.desc()));
                }
                if(AssertUtils.isNotNull(visaResponse.getSite())){
                    Arrays.stream(TerminologyConfigEnum.SITE.values()).filter(value->value.name().equals(visaResponse.getSite())).forEach(value->visaResponse.setSite(value.desc()));
                }
                if(AssertUtils.isNotNull(visaResponse.getBusinessType())){
                    Arrays.stream(TerminologyConfigEnum.BUSINESS_TYPE.values()).filter(value->value.name().equals(visaResponse.getBusinessType())).forEach(value->visaResponse.setBusinessType(value.desc()));
                }
            });
            BasePageResponse<ApplyPageResponse> responseBasePageResponse =BasePageResponse.getData(applyPageRequest.getCurrentPage(),applyPageRequest.getPageSize(),integer,vpsResponses);
            responseResultObject.setData(responseBasePageResponse);
        }
        return responseResultObject;
    }

    @Override
    public ResultObject saveApply(ApplyRequest applyRequest) {
        this.getLogger().info("保存下单记录,请求数据为:{}", JSON.toJSONString(applyRequest));
        ResultObject resultObject = new ResultObject();
        //数据校验
        vaildApplyParameter(applyRequest);
        //初始化下单
        Apply apply=null;
        if(AssertUtils.isNotNull(applyRequest.getApplyId())){
            apply=applyDao.fetchOneByApplyId(applyRequest.getApplyId());
            AssertUtils.isNotNull(this.getLogger(),apply,BaseErrorConfigEnum.APPLY_IS_NOT_NULL);
        }else{
            apply = new Apply();
        }
        ClazzUtils.copyPropertiesIgnoreNull(applyRequest,apply);
        //日期特殊处理
        if(AssertUtils.isNotNull(applyRequest.getApplyDate())){
            apply.setApplyDate(DateUtils.stringToTime(applyRequest.getApplyDate(),DateUtils.FORMATE3));
        }
        if(AssertUtils.isNotNull(applyRequest.getExpectCommentDate())){
            apply.setExpectCommentDate(DateUtils.stringToTime(applyRequest.getExpectCommentDate(),DateUtils.FORMATE3));
        }
        //持久化处理
        if(AssertUtils.isNotEmpty(applyRequest.getApplyId())){
            apply.setUpdatedDate(System.currentTimeMillis());
            applyDao.update(apply);
        }else {
            apply.setApplyStatus(AssertUtils.isNotNull(applyRequest.getApplyStatus())?applyRequest.getApplyStatus():TerminologyConfigEnum.EMAIL_STATUS.NEW.name());
            apply.setApplyId(DateUtils.getJobNumberByTime2("APPLY",null,DateUtils.FORMATE53,false));
            apply.setCreatedDate(System.currentTimeMillis());
            apply.setUpdatedDate(System.currentTimeMillis());
            applyDao.insert(apply);
        }
        return resultObject;
    }

    private void vaildApplyParameter(ApplyRequest applyRequest) {
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getApplySource(), BaseErrorConfigEnum.APPLY_SOURCE_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getApplyDate(), BaseErrorConfigEnum.APPLY_DATE_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getSite(), BaseErrorConfigEnum.SITE_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getBusinessType(), BaseErrorConfigEnum.BUSINESS_TYPE_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getApplySource(), BaseErrorConfigEnum.APPLY_SOURCE_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getExpectCommentDate(), BaseErrorConfigEnum.EXPECT_COMMENT_DATE_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getProductBelongUser(), BaseErrorConfigEnum.PRODUCT_BELONG_USER_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getExpressMethod(), BaseErrorConfigEnum.FBA_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getShopName(), BaseErrorConfigEnum.SHOP_NAME_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getProductName(), BaseErrorConfigEnum.SHOP_NAME_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getAssin(), BaseErrorConfigEnum.ASSIN_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getPrice(), BaseErrorConfigEnum.PRICE_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getMult(), BaseErrorConfigEnum.MULT_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getSearchKeyword(), BaseErrorConfigEnum.SEARCH_KEYWORD_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getPosition(), BaseErrorConfigEnum.POSITION_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(),applyRequest.getProductUrl(), BaseErrorConfigEnum.PRODUCT_URL_IS_NOT_NULL);

    }

    @Override
    public ResultObject saveOrder(OrderRequest orderRequest) {
        this.getLogger().info("保存订单,请求数据为:{}",JSON.toJSONString(orderRequest));
        ResultObject resultObject = new ResultObject();
        boolean newFlag =false;
        //数据校验
        validOrderParameter(orderRequest);
        ShopOrder order =null;
        if(AssertUtils.isNotEmpty(orderRequest.getOrderId())){
            order=orderDao.fetchOneByOrderId(orderRequest.getOrderId());
            AssertUtils.isNotNull(this.getLogger(),order,BaseErrorConfigEnum.APPLY_ID_NOT_NULL);
        }else {
            newFlag=true;
            order=new ShopOrder();
        }
        ClazzUtils.copyProperties(orderRequest,order);
        //日期特殊处理
        if(AssertUtils.isNotNull(orderRequest.getDueCommentDate())){
            order.setDueCommentDate(DateUtils.stringToTime(orderRequest.getDueCommentDate(),DateUtils.FORMATE3));
        }
        if(AssertUtils.isNotNull(orderRequest.getActualRefundDate())){
            order.setActualRefundDate(DateUtils.stringToTime(orderRequest.getActualRefundDate(),DateUtils.FORMATE3));
        }
        //持久化
        if(AssertUtils.isNotEmpty(orderRequest.getOrderId())){
            order.setUpdatedDate(System.currentTimeMillis());
            orderDao.update(order);
        }else {
            order.setOrderStatus(AssertUtils.isNotNull(order.getOrderStatus())?order.getOrderStatus():TerminologyConfigEnum.ORDER_STATUS.PENDING.name());
            order.setOrderId(DateUtils.getJobNumberByTime2("ORDER",null,DateUtils.FORMATE53,false));
            order.setCreatedDate(System.currentTimeMillis());
            order.setUpdatedDate(System.currentTimeMillis());
            orderDao.insert(order);
        }

        //更新账号余额
        if(newFlag && AssertUtils.isNotEmpty(orderRequest.getAccountId())){
           Account account =  accountDao.fetchOneByAccountId(orderRequest.getAccountId());
           //最近下单日期
            account.setRecentlyNoCommentOrderDate(System.currentTimeMillis());
           //查询关联的卡
           if(AssertUtils.isNotEmpty(account.getVisaCardId())){
               String from="USD";
               //站点
               if("JP".equals(account.getSite())){
                   from="JPY";
               }else if("UK".equals(account.getSite())){
                   from="GBP";
               }else if("DE".equals(account.getSite()) || "FR".equals(account.getSite())){
                   from="EUR";
               }
               ExchangeRate exchangeRate =iExchangeRateDao.queryOneExchangeRate(from,"USD");
               AssertUtils.isNotNull(this.getLogger(),exchangeRate,BaseErrorConfigEnum.EXCHANGE_RATE_NOT_CONFIG_NULL);
               VisaCard visaCard = visaCardDao.fetchOneByVisaCardId(account.getVisaCardId());
               visaCard.setUseAmount(visaCard.getUseAmount().add(order.getAmount().multiply(exchangeRate.getRate())));
               visaCard.setBalanceAmount(visaCard.getBalanceAmount().subtract(order.getAmount().multiply(exchangeRate.getRate())));
               visaCardDao.update(visaCard);
               //更新账号
               accountDao.update(account);
           }
        }
        //订单被取消-卡余额回归
        if(!newFlag && AssertUtils.isNotEmpty(orderRequest.getAccountId()) && TerminologyConfigEnum.ORDER_STATUS.CANCELLED.name().equals(orderRequest.getOrderStatus())) {
            Account account = accountDao.fetchOneByAccountId(orderRequest.getAccountId());
            //查询关联的卡
            if (AssertUtils.isNotEmpty(account.getVisaCardId())) {
                String from = "USD";
                //站点
                if ("JP".equals(account.getSite())) {
                    from = "JPY";
                } else if ("UK".equals(account.getSite())) {
                    from = "GBP";
                } else if ("DE".equals(account.getSite()) || "FR".equals(account.getSite())) {
                    from = "EUR";
                }
                ExchangeRate exchangeRate = iExchangeRateDao.queryOneExchangeRate(from, "USD");
                AssertUtils.isNotNull(this.getLogger(), exchangeRate, BaseErrorConfigEnum.EXCHANGE_RATE_NOT_CONFIG_NULL);
                VisaCard visaCard = visaCardDao.fetchOneByVisaCardId(account.getVisaCardId());
                visaCard.setUseAmount(visaCard.getUseAmount().subtract(order.getAmount().multiply(exchangeRate.getRate())));
                visaCard.setBalanceAmount(visaCard.getBalanceAmount().add(order.getAmount().multiply(exchangeRate.getRate())));
                visaCardDao.update(visaCard);
            }
        }
        return resultObject;
    }

    private void validOrderParameter(OrderRequest orderRequest) {
        AssertUtils.isNotNull(this.getLogger(), orderRequest.getAccountSource(), BaseErrorConfigEnum.PRODUCT_URL_IS_NOT_NULL);
        //来自内部
        if(TerminologyConfigEnum.ACCOUNT_SOURCE.INSIDE.name().equals(orderRequest.getAccountSource())){
            AssertUtils.isNotNull(this.getLogger(), orderRequest.getAccountId(), BaseErrorConfigEnum.ORDER_ACCOUNT_NOT_NULL);
        }
        if(TerminologyConfigEnum.ACCOUNT_SOURCE.OUTSIDE.name().equals(orderRequest.getAccountSource())){
            AssertUtils.isNotNull(this.getLogger(), orderRequest.getThirdProviderId(), BaseErrorConfigEnum.ORDER_PROVIDER_NOT_NULL);
        }
        AssertUtils.isNotNull(this.getLogger(), orderRequest.getSite(), BaseErrorConfigEnum.SITE_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(), orderRequest.getAmount(), BaseErrorConfigEnum.ORDER_AMOUNT_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(), orderRequest.getOptionUserName(), BaseErrorConfigEnum.OPTION_USER_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(), orderRequest.getDueCommentDate(), BaseErrorConfigEnum.DUE_REVIEW_DATE_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(), orderRequest.getApplyId(), BaseErrorConfigEnum.APPLY_ID_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(), orderRequest.getDueCommissionAmount(), BaseErrorConfigEnum.DUE_REFUND_COMMISSION_IS_NOT_NULL);
        AssertUtils.isNotNull(this.getLogger(), orderRequest.getExchangeRate(), BaseErrorConfigEnum.EXCHANGE_RATE_NOT_NULL);
    }

    @Override
    public ResultObject<OrderPageResponse> queryOrderDetail(String orderId) {
        ResultObject<OrderPageResponse> resultObject = new ResultObject<>();
        OrderPage orderPage = iOrderDao.queryOrderDetail(orderId);
        if(AssertUtils.isNotNull(orderPage)){
            OrderPageResponse orderPageResponse = (OrderPageResponse)this.converterObject(orderPage,OrderPageResponse.class);
            if(AssertUtils.isNotNull(orderPageResponse.getApplyStatus())){
                Arrays.stream(TerminologyConfigEnum.APPLY_STATUS.values()).filter(value->value.name().equals(orderPageResponse.getApplyStatus())).forEach(value->orderPageResponse.setApplyStatus(value.desc()));
            }
            if(AssertUtils.isNotNull(orderPageResponse.getApplySource())){
                Arrays.stream(TerminologyConfigEnum.APPLY_SOURCE.values()).filter(value->value.name().equals(orderPageResponse.getApplySource())).forEach(value->orderPageResponse.setApplySource(value.desc()));
            }
            if(AssertUtils.isNotNull(orderPageResponse.getSite())){
                Arrays.stream(TerminologyConfigEnum.SITE.values()).filter(value->value.name().equals(orderPageResponse.getSite())).forEach(value->orderPageResponse.setSite(value.desc()));
            }
            if(AssertUtils.isNotNull(orderPageResponse.getBusinessType())){
                Arrays.stream(TerminologyConfigEnum.BUSINESS_TYPE.values()).filter(value->value.name().equals(orderPageResponse.getBusinessType())).forEach(value->orderPageResponse.setBusinessType(value.desc()));
            }
            resultObject.setData(orderPageResponse);
        }
        return resultObject;
    }

    @Override
    public ResultObject<ApplyPageResponse> queryApplyDetail(String applyId) {
        ResultObject<ApplyPageResponse> resultObject = new ResultObject<>();
        Apply apply = applyDao.fetchOneByApplyId(applyId);
        if(AssertUtils.isNotNull(apply)){
            ApplyPageResponse applyPageResponse=(ApplyPageResponse)this.converterObject(apply,ApplyPageResponse.class);
            resultObject.setData(applyPageResponse);
        }
        return resultObject;
    }
    /**
     * 导出订单
     * @param orderExportRequest 导出订单
     * @return
     */
    @Override
    public ResultObject exportPageOrderList(HttpServletResponse response, OrderExportRequest orderExportRequest) {
        List<OrderPage> orderPages = new ArrayList<>();
        if(AssertUtils.isNotEmpty(orderExportRequest.getOrderIds())){
            String[] split = orderExportRequest.getOrderIds().split(",");
            orderPages=iOrderDao.queryOrderListByIds(Arrays.asList(split));
        }else {
            OrderPageRequest orderPageRequest =new OrderPageRequest();
            ClazzUtils.copyPropertiesIgnoreNull(orderExportRequest,orderPageRequest);
            orderPageRequest.setPageSize(1000);
            orderPages=iOrderDao.queryPageOrderList(orderPageRequest);
        }
        //导出反馈订单
        exportFeedbackOrderList(response, orderPages);
        return new ResultObject();
    }

    /**
     * 导出反馈订单
     * @param response
     * @param orderPages
     */
    private void exportFeedbackOrderList(HttpServletResponse response, List<OrderPage> orderPages) {
        try {
            Resource resource = new ClassPathResource("order_feedback.xlsx");
            this.getLogger().info("模板路径:{}",resource.getURL().getPath());
            InputStream inputStream = resource.getURL().openStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            //得到工作表
            XSSFSheet sheet = workbook.getSheetAt(0);

            int num = 0;
            int total = AssertUtils.isNotNull(orderPages) && orderPages.size() > 0 ? orderPages.size() + 2 : sheet.getLastRowNum();
            System.out.println("====================================exports size================================================");
            System.out.println("total:" + total);
            System.out.println("====================================exports size================================================");
            //TODO 更改行数，
            for (int i = 1; i < total; i++) {
                if (!(orderPages.size() > num && AssertUtils.isNotNull(orderPages.get(num)))) {
                    break;
                }
                OrderPage orderPage = orderPages.get(num);
                num++;
                Row writeRow = sheet.getRow(i);
                if (!AssertUtils.isNotNull(writeRow)) {
                    Row sheetRow = sheet.getRow( i- 1);
                    writeRow = sheet.createRow(i);
                    copyRow(workbook, sheet, sheetRow, writeRow, false);
                }
                writeRow.getCell(0).setCellValue(i);
                //下单日期
                String createDate = DateUtils.timeStrToString(orderPage.getCreatedDate(),DateUtils.FORMATE3);
                writeRow.getCell(1).setCellValue(createDate);
                //站点
                writeRow.getCell(2).setCellValue(orderPage.getSite());
                //订单号
                writeRow.getCell(3).setCellValue(orderPage.getOrderNo());
                //下单账号来源
                writeRow.getCell(4).setCellValue(TerminologyConfigEnum.ACCOUNT_SOURCE.valueOf(orderPage.getAccountSource()).desc());
                //渠道
                writeRow.getCell(5).setCellValue(orderPage.getProviderCompanyName());
                //店铺名
                writeRow.getCell(6).setCellValue(orderPage.getShopName());
                //产品负责人
                writeRow.getCell(7).setCellValue(orderPage.getProductBelongUser());
                //产品名称
                writeRow.getCell(8).setCellValue(orderPage.getProductName());
                //assin
                writeRow.getCell(9).setCellValue(orderPage.getAssin());
                //产品页面链接
                writeRow.getCell(10).setCellValue(orderPage.getProductUrl());
                //产品价格
                writeRow.getCell(11).setCellValue(orderPage.getPrice()+"");
                //订单数量
                writeRow.getCell(12).setCellValue("1");
                //关键词
                writeRow.getCell(13).setCellValue(orderPage.getSearchKeyword());
                //关键词位置
                writeRow.getCell(14).setCellValue(orderPage.getPosition());
                //业务类型
                writeRow.getCell(15).setCellValue(TerminologyConfigEnum.BUSINESS_TYPE.valueOf(orderPage.getBusinessType()).desc());
                //期望上评日期
                writeRow.getCell(16).setCellValue(DateUtils.timeStrToString(orderPage.getDueCommentDate()));
                //reviews
                writeRow.getCell(17).setCellValue(orderPage.getCommentTitle());
                //reviews
                writeRow.getCell(18).setCellValue(orderPage.getImageUrl1());
                //佣金
                writeRow.getCell(19).setCellValue(orderPage.getDueCommissionAmount()+"");
                //汇率
                writeRow.getCell(20).setCellValue(orderPage.getExchangeRate()+"");
                //订单状态
                writeRow.getCell(21).setCellValue(TerminologyConfigEnum.ORDER_STATUS.valueOf(orderPage.getOrderStatus()).desc());
               //处理人
                writeRow.getCell(22).setCellValue(orderPage.getOptionUserName());

            }
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(DateUtils.dateToString(new Date(),DateUtils.FORMATE55)+"反馈订单.xls", "UTF-8"));
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.close();
            inputStream.close();
            byteArrayOutputStream.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 导出第三方返款订单
     * @param response
     * @param orderExportRequest
     * @return
     */
    @Override
    public ResultObject exportRefundOrderList(HttpServletResponse response, OrderExportRequest orderExportRequest) {
        List<OrderPage> orderPages = new ArrayList<>();
        if(AssertUtils.isNotEmpty(orderExportRequest.getOrderIds())){
            String[] split = orderExportRequest.getOrderIds().split(",");
            orderPages=iOrderDao.queryOrderListByIds(Arrays.asList(split));
        }else {
            OrderPageRequest orderPageRequest =new OrderPageRequest();
            ClazzUtils.copyPropertiesIgnoreNull(orderExportRequest,orderPageRequest);
            orderPageRequest.setPageSize(1000);
            orderPages=iOrderDao.queryPageOrderList(orderPageRequest);
        }
        //导出反馈订单
        exportThirdRefundOrderList(response, orderPages);
        return new ResultObject();
    }


    /**
     * 导出第三方反馈订单
     * @param response
     * @param orderPages
     */
    private void exportThirdRefundOrderList(HttpServletResponse response, List<OrderPage> orderPages) {
        try {
            Resource resource = new ClassPathResource("third_service_refund.xlsx");
            this.getLogger().info("模板路径:{}",resource.getURL().getPath());
            InputStream inputStream = resource.getURL().openStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            //得到工作表
            XSSFSheet sheet = workbook.getSheetAt(0);

            int num = 0;
            int total = AssertUtils.isNotNull(orderPages) && orderPages.size() > 0 ? orderPages.size() + 2 : sheet.getLastRowNum();
            System.out.println("====================================exports size================================================");
            System.out.println("total:" + total);
            System.out.println("====================================exports size================================================");
            //TODO 更改行数，
            for (int i = 1; i < total; i++) {
                if (!(orderPages.size() > num && AssertUtils.isNotNull(orderPages.get(num)))) {
                    break;
                }
                OrderPage orderPage = orderPages.get(num);
                num++;
                Row writeRow = sheet.getRow(i);
                if (!AssertUtils.isNotNull(writeRow) || !AssertUtils.isNotNull(writeRow.getCell(0))) {
                    Row sheetRow = sheet.getRow( i- 1);
                    writeRow = sheet.createRow(i);
                    copyRow(workbook, sheet, sheetRow, writeRow, false);
                }
                //店铺名
                writeRow.getCell(0).setCellValue(i);
                //店铺名
                writeRow.getCell(1).setCellValue(orderPage.getShopName());
                //站点
                writeRow.getCell(2).setCellValue(orderPage.getSite());
                //产品名称
                writeRow.getCell(3).setCellValue(orderPage.getProductName());
                //产品负责人
                writeRow.getCell(4).setCellValue(orderPage.getProductBelongUser());
                //订单号
                writeRow.getCell(5).setCellValue(orderPage.getOrderNo());
                //下单日期
                String createDate = DateUtils.timeStrToString(orderPage.getCreatedDate(),DateUtils.FORMATE3);
                writeRow.getCell(6).setCellValue(createDate);
                //产品SKU
                writeRow.getCell(7).setCellValue("");
                //assin
                writeRow.getCell(8).setCellValue(orderPage.getAssin());
                //产品价格
                writeRow.getCell(9).setCellValue(orderPage.getAmount()+"");
                //渠道
                if(TerminologyConfigEnum.ACCOUNT_SOURCE.OUTSIDE.name().equals(orderPage.getAccountSource())){
                    writeRow.getCell(10).setCellValue(orderPage.getProviderContactName());
                    //刷单人联系方式
                    String contactInfo="";
                    if(AssertUtils.isNotNull(orderPage.getProviderContactMethod()) && AssertUtils.isNotNull(orderPage.getProviderContactNo())){
                        contactInfo=orderPage.getProviderContactMethod()+":"+orderPage.getProviderContactNo();
                    }
                    writeRow.getCell(11).setCellValue(contactInfo);
                    //刷单公司
                    writeRow.getCell(12).setCellValue(orderPage.getProviderCompanyName());
                }else {
                    writeRow.getCell(10).setCellValue(orderPage.getOptionUserName());
                    //刷单人联系方式
                    writeRow.getCell(11).setCellValue("");
                    //刷单公司
                    writeRow.getCell(12).setCellValue("");
                }
                //汇率
                writeRow.getCell(13).setCellValue(AssertUtils.isNotNull(orderPage.getExchangeRate())?orderPage.getExchangeRate()+"":"0");
                //佣金
                writeRow.getCell(14).setCellValue(AssertUtils.isNotNull(orderPage.getDueCommissionAmount())?orderPage.getDueCommissionAmount()+"":"0");
                //返款方式
                writeRow.getCell(15).setCellValue(orderPage.getProviderRefundMethod());
                //留评日期
                writeRow.getCell(16).setCellValue(DateUtils.timeStrToString(orderPage.getActulCommentDate()));
                //评论截图
                writeRow.getCell(17).setCellValue(orderPage.getImageUrl1());
                //订单状态
                writeRow.getCell(18).setCellValue(TerminologyConfigEnum.ORDER_STATUS.valueOf(orderPage.getOrderStatus()).desc());
                //总金额
                BigDecimal productAmount=new BigDecimal(0);
                if(AssertUtils.isNotNull(orderPage.getAmount()) && AssertUtils.isNotNull(orderPage.getExchangeRate())){
                    productAmount= orderPage.getAmount().multiply(orderPage.getExchangeRate());
                }
                writeRow.getCell(19).setCellValue(productAmount+"");
                //总金额
                BigDecimal amount=new BigDecimal(0);
                if(AssertUtils.isNotNull(orderPage.getAmount()) && AssertUtils.isNotNull(orderPage.getExchangeRate())){
                    amount= orderPage.getAmount().multiply(orderPage.getExchangeRate());
                }
                if(AssertUtils.isNotNull(orderPage.getDueCommissionAmount())){
                    amount= amount.add(orderPage.getDueCommissionAmount());
                }
                writeRow.getCell(20).setCellValue(amount+"");
                //返款日期
                writeRow.getCell(21).setCellValue(DateUtils.timeStrToString(orderPage.getActualRefundDate()));
            }
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(DateUtils.dateToString(new Date(),DateUtils.FORMATE55)+"第三方返款表.xls", "UTF-8"));
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.close();
            inputStream.close();
            byteArrayOutputStream.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }



    //导出方法
    public static void copyRow(Workbook wb, Sheet sheet, Row fromRow, Row toRow, boolean copyValueFlag) {
        toRow.setHeight(fromRow.getHeight());
        for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
            CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
            if (cellRangeAddress.getFirstRow() == fromRow.getRowNum()) {
                CellRangeAddress newCellRangeAddress = new CellRangeAddress(toRow.getRowNum(), (toRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())), cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
                sheet.addMergedRegion(newCellRangeAddress);
            }
        }
        for (Iterator cellIt = fromRow.cellIterator(); cellIt.hasNext(); ) {
            Cell tmpCell = (Cell) cellIt.next();
            Cell newCell = toRow.createCell(tmpCell.getColumnIndex());
            copyCell(wb, tmpCell, newCell, copyValueFlag);
        }
    }

    public static void copyCell(Workbook wb, Cell srcCell, Cell distCell, boolean copyValueFlag) {
        CellStyle newstyle = wb.createCellStyle();
        newstyle.cloneStyleFrom(srcCell.getCellStyle());
        distCell.setCellStyle(newstyle);
        if (srcCell.getCellComment() != null) {
            distCell.setCellComment(srcCell.getCellComment());
        }
        int srcCellType = srcCell.getCellType();
        distCell.setCellType(srcCellType);
        if (copyValueFlag) {
            if (srcCellType == HSSFCell.CELL_TYPE_NUMERIC) {
                if (HSSFDateUtil.isCellDateFormatted(srcCell)) {
                    distCell.setCellValue(srcCell.getDateCellValue());
                } else {
                    distCell.setCellValue(srcCell.getNumericCellValue());
                }
            } else if (srcCellType == HSSFCell.CELL_TYPE_STRING) {
                distCell.setCellValue(srcCell.getRichStringCellValue());
            } else if (srcCellType == HSSFCell.CELL_TYPE_BLANK) {
            } else if (srcCellType == HSSFCell.CELL_TYPE_BOOLEAN) {
                distCell.setCellValue(srcCell.getBooleanCellValue());
            } else if (srcCellType == HSSFCell.CELL_TYPE_ERROR) {
                distCell.setCellErrorValue(srcCell.getErrorCellValue());
            } else if (srcCellType == HSSFCell.CELL_TYPE_FORMULA) {
                distCell.setCellFormula(srcCell.getCellFormula());
            } else {
            }
        }
    }

}
